import datetime

from sqlalchemy import String
from sqlalchemy.dialects.mysql import INTEGER, DATETIME, TEXT

from shop.model import db


class Searchwords(db.Model):
    __tablename__ = 'searchwords'

    id = db.Column(INTEGER(11), primary_key=True)
    phone = db.Column(String(20))
    user_id = db.Column(INTEGER(11))
    word = db.Column(String(50), index=True)
    save_time = db.Column(DATETIME)
    ip = db.Column(String(20))


def save_one_searchwords(one_search_word, ip_addr):
    sw = Searchwords()
    sw.save_time = datetime.datetime.now()
    sw.word = one_search_word
    sw.ip = ip_addr
    db.session.add(sw)
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        db.session.remove()
